package org.longkey.portal
{
	import flash.display.DisplayObject;
	import flash.utils.Dictionary;
	import flash.utils.getTimer;
	import flash.utils.setTimeout;
	
	import mx.core.FlexGlobals;
	import mx.core.UIComponent;
	import mx.rpc.AsyncToken;
	import mx.rpc.Responder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	import spark.components.TitleWindow;
	

	public class Portal
	{
		private static var httpService:HTTPService;
		private static var responder:Responder;
		private static var ret:Object;
		private static var datafmt:String = "php";
		private static var proxyUrl:String;
		private static var callback:Function;
		
		public static function get result():Object{
			return ret;
		}
		
		public static function init(contextPath:String):void{
			httpService = new HTTPService();
			var idx:int = contextPath.indexOf("://");
			if(idx < 0){
				idx = 0;
			}
			idx = contextPath.indexOf("/",idx);
			var suffix:String = "";
			if(idx < contextPath.length){
				suffix = contextPath.substr(idx+1);
			}
			if(suffix.length == 0){//cust with independent domain
				proxyUrl = contextPath + "proxy.php";
			}
			else if(suffix.indexOf("/p/") > 0){//cust without independent domain
				proxyUrl = contextPath + "proxy.php";
			}
			else{//uisp domain
				proxyUrl = contextPath + "p/common/proxy.php";
			}
			httpService.resultFormat = "text";
			responder = new Responder(Portal.handleResult, Portal.handleFault);
			
			
		}
		
		private static function handleResult(event:ResultEvent):void{
			if(datafmt == "json"){
				ret = JSON.parse(event.result as String);
			}
			else if(datafmt == "php"){
				ret = PHPSerializer.unserialize(event.result as String);
			}
			else{
				ret = event.result;
			}
			MaskUtil.hide();
			if(Portal.callback != null){
				Portal.callback(ret);
			}
		}
		
		private static function handleFault(event:FaultEvent):void{
			MaskUtil.hide();
			MaskUtil.error("服务器异常，请稍后再试。", 3000);
		}
		
		public static function execjava(callback:Function, ids:String, params:Object=null, custId:String=null):void{
			var parameters:Object = new Object();
			parameters["__ids"] = ids;
			if(custId != null && custId.length > 0){
				parameters["custId"] = custId;
			}
			parameters["__params"] = PHPSerializer.serialize(params);
			Portal.ajax(proxyUrl, parameters, "POST", callback);
		}

		private static function ajax(url:String, parameters:Object, httpMethod:String, callback:Function, fmt:String="php"):void{
			Portal.httpService.url = url;
			Portal.httpService.method = httpMethod;
			Portal.ret = null;
			Portal.datafmt = fmt;
			Portal.callback = callback;
			MaskUtil.wait();
			var token:AsyncToken = httpService.send(parameters);
			token.addResponder(responder);
		}
	}
}